#ifndef _CLIENT_
#define _CLIENT_
#include "ExampleClient.h"
#include "request.hpp"

//static threadpool<rawMessage> tp;

static unsigned long long count=0;

bool ExampleClient::ReadReady()
{
    /*
    //read the size of data(4 bytes).
    while(!sizeIsRead)
    {
        //cout<<"read the size."<<endl;
        int bytesAvil=recv(fd_,&packetSize,sizeof(int),MSG_PEEK);
        if(bytesAvil<sizeof(int))
        {
            continue;
        }
        //packetSize=ntohl(packetSize);
        recv(fd_,&packetSize,sizeof(int),0);
        packetSize=ntohl(packetSize);
        sizeIsRead=true;
        break;
    }
    while(bytes_read<packetSize)
    {
        memset(buffer,0,1024);
        int ret=recv(fd_,buffer,packetSize-bytes_read,0);
        if(ret<0)
        {
            if((errno==EAGAIN)||(errno==EWOULDBLOCK))
            {
                cout<<"read later."<<endl;
                return true;;
            }
            cout<<"can not read data."<<endl;
            return false;
        }
        else if(ret==0)
        {
            //cout<<"client close the connection."<<endl;
            return false;
        }
        else
        {
            bytes_read+=ret;
            data_buffer.append(buffer,ret);
            //cout<<data_buffer<<endl;
        }
    }
    */
    memset(buffer,0,1024);
    int ret=recv(fd_,buffer,1024,0);
    cout<<ret<<endl;
    data_buffer.append(buffer,ret);
    cout<<data_buffer<<endl;
    rawMessage *tmp=new rawMessage(data_buffer,fd_);
    tp.append(tmp);
    printf("[i] client %s:%d send a message.\n",inet_ntoa(client_addr_), client_port_);
    last_active_ = time(0);
    data_buffer.clear();
    sizeIsRead=false;
    packetSize=0;
    bytes_read=0;
    return true;
}

bool ExampleClient::WriteReady()
{
    /*
    	during heavy network I/O fds can become unwritable and subsequent calls to write() / send() will fail,
    	in this case the data which failed to send should be stored in a buffer and the operation should be
    	retried when WriteReady() is called to signal the fd is writable again (this is up to you to implement).
    */
    return true;
}

bool ExampleClient::HeartBeat()
{
    //if no operations occurred during timeout period return false to signal server to close socket
    if(static_cast<time_t>(last_active_ + timeout_) < time(0))
    {
        printf("[i] connection %s:%d has timed out\n", inet_ntoa(client_addr_), client_port_);
        return false;
    }

    return true;
}

void ExampleClient::ClientClose()
{
    close(fd_);

    printf("[-] connection %s:%d closed by client\n", inet_ntoa(client_addr_), client_port_);
}

void ExampleClient::ServerClose()
{
    close(fd_);

    printf("[-] connection %s:%d closed by server\n", inet_ntoa(client_addr_), client_port_);
}

#endif
